#!/usr/bin/perl

# Purpose:
#  Wrap lines of a Fortran code at 72 columns.
#  Print cpp commands (lines starting with `#') without modification.
#  Strip trailing comments that start with a "!" (that isn't in a string)

my $opt_d = 0 ;
if( $ARGV[0] eq "-d" ){
    $opt_d = 1 ;
    shift ;
}

require "stripcompp.pm";
StripComProc->import();

my $openquote = 0;

while(<>) {
    s/[\n\r]*$// ; #strip line-terminators
    next if m/^\s*$/ ; #skip blank lines
    # output a cpp line as-is; strip all others
    if ( /^\s*\#/ ) {
        print $_,"\n" ;
    } else {
        ( $_ ,$openquote ) = &StripComProc::stripTrailingComment( $_,$openquote,$opt_d );
        # stripTrailing removes the trailing linefeed so it put it back on output
        print &strip72(),"\n" ;
    }
}

sub strip72 {
    my $out ;
    ## gross hack: change a leading tab to spaces so it won't get misinterpreted
    ## as a comment in the "next if" below. <dbs>
    s/^\t/      /;
    # look for Fortran comment lines being with "C", "c" or "*" or "!"
    # or empty continuation lines and don't output them
    my $match1 = chr(33).chr(36)."OMP";
    my $match2 = chr(33).chr(36)."omp";
    next if ( m/^[c\*]/i || (m/^\s*!/ && !(/\Q$match1\E/) && !(/\Q$match2\E/)) || m/^.....[^0]\s*$/ );

    # break the line into 72 character pieces with continuations
    # [NOTE: some of the `substr' calls will generate Perl warnings.]
    $out = substr($_,0,72) ;
    $_ = substr($_,72) ;
    # dont output empty lines
    while ( length($_) > 0 && $_ !~ m/^\s*$/ ) {
        $out .= "\n     &" . substr($_,0,66) ;
        $_ = substr($_,66) ;
    }

    return $out ;
}


